//深拷贝 deep copy
//和浅拷贝相比，增加了3个方法：析构函数、拷贝构造函数、=重载
//类的某属性是指针（动态存储），为了避免同类对象之间赋值产生的浅拷贝问题，需要定义拷贝构造函数、重载=运算符、定义析构函数。
#include <iostream>
using namespace std;
class DcopySample
{
public:
    DcopySample():m_ptr(NULL)
    {
    }
    DcopySample(int i)
    {
        m_ptr=new int(i);
    }
    //析构函数
    ~DcopySample()
    {
        delete m_ptr;
    }
    //拷贝构造函数
    DcopySample(const DcopySample& other)
    {
        this->m_ptr = new int(*(other.m_ptr));
    }
    //赋值运算符=重载
    DcopySample& operator=(const DcopySample& other)
    {
        //如果*this和other二者内存地址相同，则它们是同一对象
        if(this == &other)
            return *this;
        //否则，释放this的动态空间
        //delete this->m_ptr;
        //this->m_ptr=new int(*(other.m_ptr));
        if(this->m_ptr== NULL)
            this->m_ptr=new int(*(other.m_ptr));
        else
            *(this->m_ptr) = *(other.m_ptr);
        return *this;
    }
    void setValue(int i)
    {
        *m_ptr=i;
    }
    int getValue() const
    {
        return *m_ptr;
    }
private:
    int *m_ptr;
};

int main()
{
    DcopySample obj1(5);
    DcopySample obj2(obj1);
    DcopySample obj3;
    obj3=obj1;
    cout<< "Before obj1="<<obj1.getValue()<<endl;
    cout<< "Before obj2="<<obj2.getValue()<<endl;
    cout<< "Before obj3="<<obj3.getValue()<<endl;
    obj1.setValue(13);
    cout<< "After obj1="<<obj1.getValue()<<endl;
    cout<< "After obj2="<<obj2.getValue()<<endl;
    cout<< "After obj3="<<obj3.getValue()<<endl;
    obj2.setValue(-7);
    cout<< "Last obj1="<<obj1.getValue()<<endl;
    cout<< "Last obj2="<<obj2.getValue()<<endl;
    cout<< "Last obj3="<<obj3.getValue()<<endl;
    return 0;
}